var ifmIndex = require('../models/ifmIndex.js');
var cfmIndex = require('../models/cfmIndex.js');
var ObjectID = require("mongodb").ObjectID;

exports.on = function(req, res) {
    console.log('user-intro');
    checkExistence(req,res,function(state,doc){
        var ifm_index =doc;
        cfmIndex.get({_id : ObjectID(req.params.id)},function(err,doc){
            var cfm_index = doc[0];
            res.render('user-intro', {
                title: 'Project Owned',
                user : req.session.user,
                state : state,
                ifmIndex : ifm_index,
                cfmIndex : cfm_index,
                success : "",
                error : ""
            });
        });
    })
};


checkExistence = function(req,res,callback){
    var filter = {};
    filter["user"] = req.params.user;

    ifmIndex.get(filter,function(err,doc){
        if(doc[0] === undefined){
            //还没有初始化ifm
            ifmIndex.create(filter,function(err,doc){
                return res.redirect(req.url);
            });
        }else{
            //初始化了但是没有那个id
            if(doc[0][ObjectID(req.params.id)] != undefined){
                callback(true,doc[0][ObjectID(req.params.id)]);
            }else{
                callback(false,null);
            }
        }
    });
}